import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import { Row, Col, Input, Button, Table, Card, message, Icon, Pagination, Form, Select, DatePicker } from 'antd';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import { FormattedMessage } from 'umi-plugin-react/locale';
import styles from './Home.less';
import PageLoading from '@/components/PageLoading';

const IntroduceRow = React.lazy(() => import('./IntroduceRow'));
const ProportionSales = React.lazy(() => import('./ProportionSales'));
const { RangePicker } = DatePicker;

const columns = [
  {
    title: '热度变化',
    dataIndex: 'hotChange',
    key: 'hotChange',
    sorter: true,
    render: (text, row) => {
      if (row.yesterdayCount >= row.beforeYesterdayCount) {
        return <Icon type="arrow-up" style={{ color: 'green' }} />;
      };
      return <Icon type="arrow-down" style={{ color: 'red' }} />;
    },
    align: 'center',
  },
  {
    title: '知识点标准问',
    dataIndex: 'question',
    key: 'question',
    defaultSortOrder: 'descend',
    width: 200,
    sorter: (a, b) => (a.question && b.question ? a.question.length - b.question.length : ''),
    align: 'center',
  },
  {
    title: '命中次数',
    dataIndex: 'yesterdayCount',
    key: 'yesterdayCount',
    defaultSortOrder: 'descend',
    sorter: (a, b) => a.yesterdayCount - b.yesterdayCount,
    align: 'center',
  },
  {
    title: '环比变化',
    dataIndex: 'momChange',
    key: 'momChange',
    render: (text, row) => {
      if (row.yesterdayCount >= row.beforeYesterdayCount) {
        if (row.beforeYesterdayCount == 0) {
          return (
            <span style={{ marginRight: 4 }}>
              {row.yesterdayCount}%
              <Icon type="caret-up" style={{ color: 'green' }} />
            </span>
          );
        } else {
          return (
            <span style={{ marginRight: 4 }}>
              {row.yesterdayCount / row.beforeYesterdayCount}%
              <Icon type="caret-up" style={{ color: 'green' }} />
            </span>
          );
        }
      };
      return (
        <span style={{ marginRight: 4 }}>
          {((row.beforeYesterdayCount / row.yesterdayCount) * 100).toFixed(2)}%
          <Icon type="caret-down" style={{ color: 'green' }} />
        </span>
      );
    },
    align: 'center',
    defaultSortOrder: 'descend',
    sorter: (a, b) => parseInt(a.momChange) - parseInt(b.momChange),
  },
];

@connect(({ home, loading }) => ({
  home,
  loading: loading.effects['home/fetch'],
}))
class Home extends Component {
  state = {
    salesType: 'all',
    page: 1,
    homeObj: {},
    items: [],
    total: 0,
    loading: true,
  };

  componentDidMount() {
    const that = this;
    const { dispatch } = this.props;
    const searchKey = that.state.searchKey;
    const page = that.state.page;
    let home = null;
    let storage = window.localStorage.getItem('currentUser');
    let currentUser = JSON.parse(storage);
    // this.reqRef = requestAnimationFrame(() => {
    //   dispatch({
    //     type: 'home/fetch',
    //     payload: { robotId: currentUser.robotId },
    //     callback: res => {
    //       home = res;
    //     },
    //   }).then(() => {
    //     dispatch({
    //       type: 'home/fakeTableDataList',
    //       payload: { robotId: currentUser.robotId, key: searchKey, page: page, limit: 10 },
    //       callback: res => {
    //         this.setState({
    //           items: res.items,
    //           total: res.total,
    //           loading: false,
    //           homeObj: home,
    //         });
    //       },
    //     });
    //   });
    // });
  }

  handleChangeSalesType = e => {
    this.setState({ salesType: e.target.value });
  };

  // 昨日热点问题搜索排序点击操作
  selectDate = (pagination, filters, sorter) => {
    const pager = { ...this.state.pagination };
    pager.current = pagination.current;
    this.setState({ pagination: pager });
  };

  // 昨日热点问题搜索
  searchData = () => {
    const that = this;
    const searchKey = that.state.searchKey;
    const page = this.state.page;
    const { dispatch, currentUser } = this.props;
    // dispatch({
    //   type: 'home/fakeTableDataList',
    //   payload: { robotId: currentUser.robotId, key: searchKey, page: page, limit: 10 },
    //   callback: res => {
    //     this.setState({
    //       items: res.items,
    //       total: res.total,
    //       loading: false,
    //     });
    //   },
    // });
  };

  // 搜索框动态输入
  inputVal(val) {
    this.setState({ searchKey: val.target.value });
  }

  // 翻页
  fanye(e) {
    this.setState({ page: e }, () => {
      this.searchData();
    });
  }

  render() {
    const { items, total, homeObj, loading } = this.state;
    const { home } = this.props;
    const { visitorTup, chatCountTup, matchRateTup, unknownCountTup, hitCountTup } = home;
    let questionTotalNumber = 0;
    if (JSON.stringify(hitCountTup) !== '{}') {
      for (let i of hitCountTup) {
        questionTotalNumber = questionTotalNumber + i.y;
      };
      if (questionTotalNumber == 0) {
        hitCountTup.push({ x: '暂无数据', y: 1 });
      };
    };

    return (
      <GridContent>
        <Row>
          <Col span={24} style={{ textAlign: 'right', marginBottom: 10 }}>
            <Form layout={'inline'}>
              <Form.Item>
                <Select placeholder={'请选择机器人'} style={{ width: 200 }}>
                  <Select.Option value={1}>1</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item>
                <RangePicker />
              </Form.Item>
              <Form.Item>
                <Select placeholder={'请选择触发方式'} defaultValue={''}>
                  <Select.Option value={''}>全部触发方式</Select.Option>
                  <Select.Option value={1}>点击触发</Select.Option>
                  <Select.Option value={2}>输入触发</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item>
                <Button type={'primary'}>查看</Button>
              </Form.Item>
            </Form>
          </Col>
        </Row>
        <Suspense fallback={<PageLoading />}>
          <IntroduceRow loading={loading} visitData={home} />
        </Suspense>
        <div className={styles.twoColLayout}>
          <Row gutter={24}>
            <Col xl={12} lg={24} md={24} sm={24} xs={24}>
              <Suspense fallback={null}>
                <ProportionSales
                  loading={loading}
                  salesPieData={hitCountTup}
                  handleChangeSalesType={this.handleChangeSalesType}
                />
              </Suspense>
            </Col>
            <Col xl={12} lg={24} md={24} sm={24} xs={24}>
              <Suspense fallback={null}>
                <Card
                  loading={loading}
                  className={styles.salesCard}
                  bordered={false}
                  title={<FormattedMessage id="app.home.hot-questions-yesterday" />}
                  bodyStyle={{ padding: 24 }}
                >
                  <Row>
                    <Col xs={8}>
                      <Input
                        placeholder="请输入搜索内容"
                        onPressEnter={value => this.searchData(value)}
                        onChange={e => this.inputVal(e)}
                        allowClear
                      />
                    </Col>
                    <Col xs={8}>
                      <Button
                        type="primary"
                        htmlType="button"
                        style={{ marginLeft: '10px' }}
                        onClick={this.searchData}
                      >
                        搜索
                      </Button>
                    </Col>
                  </Row>
                  <Table
                    dataSource={items}
                    rowKey="key"
                    onChange={this.selectDate}
                    columns={columns}
                    style={{ marginTop: '10px' }}
                    bordered
                    size="small"
                    pagination={false}
                    algin="center"
                  />
                  <Pagination
                    total={parseInt(total)}
                    onChange={e => this.fanye(e)}
                    style={{ float: 'right', marginTop: '10px' }}
                  />
                </Card>
              </Suspense>
            </Col>
          </Row>
        </div>
      </GridContent>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Home);
